package com.moshang.blog.core.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.moshang.blog.core.constant.SMSContentUtil;

import java.io.IOException;
import java.util.Random;

/**
 * @program: blog
 * @description: 发送手机短信工具类
 * @author: moshang
 * @create: 2019-02-11 15:47
 **/
public class SendSMSUtils {

    /**
     * 指定模板ＩＤ发送短信
     * @param number 用户手机号
     * @return OK 成功  null 失败
     */
    public static String sendMesModel(String number){
        try {
            //验证码
            String str = "";
            // 签名参数未提供或者为空时，会使用默认签名发送短信
            //随机生成6位的验证码
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                str += random.nextInt(10);
            }
            //{参数}
            String[] params = {str , "1" };
            SmsSingleSender ssender = new SmsSingleSender(SMSContentUtil.APPID, SMSContentUtil.APPKEY);
            SmsSingleSenderResult result = ssender.sendWithParam("86", number,
                    SMSContentUtil.TTEMPLATEID, params, SMSContentUtil.SMSSIGN, "", "");
            /*转换返回结果,用JSONObject解析json数据，0代表成功，非0失败*/
            JSONObject json = JSONObject.parseObject(result.toString());
            String state = json.getString("result");
            if ("0".equals(state)) {

                System.out.println("短信发送成功！");
                return str;
            } else {
                System.out.println("短信发送失败！");
                return result.errMsg;
            }
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }
        return null;
    }


}
